<template>
  <div class="temp_deatil" v-loading="loading">
    <div class="detail_left">
      <div class="left_top">
        <el-anchor :container="tableList" v-if="detailInfo.spaceList">
          <el-anchor-link class="first_link" href="#space">
            {{ `空间（${detailInfo.spaceList.length}）` }}
            <template #sub-link>
              <el-anchor-link
                class="second_link"
                v-for="item in detailInfo.spaceList"
                :key="item.spaceId"
                :href="`#space-${item.spaceId}`"
              >
                <p class="text-over" style="width: 160px" :title="item.spaceName">{{ item.spaceName }}</p>

                <el-popover v-if="canEdit" placement="bottom" :width="100" trigger="hover">
                  <template #default>
                    <div class="operate_btns">
                      <el-button class="operate_btn" type="primary" @click="editSpace(item)" link>编辑</el-button>
                      <el-button class="operate_btn" type="primary" @click="copySpace(item)" link>复制</el-button>
                      <el-button class="operate_btn" type="danger" @click="deleteSpace(item)" link>删除</el-button>
                    </div>
                  </template>
                  <template #reference>
                    <el-button class="more_icon" type="primary" link>
                      <el-icon>
                        <MoreFilled />
                      </el-icon>
                    </el-button>
                  </template>
                </el-popover>
              </el-anchor-link>

              <!-- <el-button
                v-if="detailInfo.spaceList.length < originLength"
                type="primary"
                @click="nextPart"
                link
                style="width: 100%"
                >查看更多{{ originLength }}</el-button
              > -->
            </template>
          </el-anchor-link>
          <el-anchor-link class="first_link" :href="`#comprehensive`" v-if="!(currTempObj.softDecorationStatus === 1)">
            {{ `综合项（${detailInfo.comprehensiveList.length}）` }}
          </el-anchor-link>
          <!-- 软装模式下-汇总明细-定位导航link -->
          <el-anchor-link class="first_link" :href="`#summary-details`" v-if="currTempObj.softDecorationStatus === 1">
            汇总明细
          </el-anchor-link>
          <el-anchor-link class="first_link" :href="`#summary`"> 预算汇总表</el-anchor-link>
        </el-anchor>
      </div>
      <div class="left_bottom" v-if="detailInfo.regularViewStatus || detailInfo.specialViewStatus">
        <div class="bottom_discount" v-if="detailInfo.regularViewStatus">
          <div>正价商品</div>
          <el-input
            v-if="detailInfo.canEdit"
            v-model="detailInfo.customerRegularDiscount"
            placeholder="请输入"
            oninput="value=value.replace(/[^\d]/g,'');"
            @change="updateDiscount"
          >
            <template #suffix>%</template>
          </el-input>
          <span v-else>{{ detailInfo.customerRegularDiscount || "-" }} %</span>
        </div>
        <div class="bottom_discount" v-if="detailInfo.specialViewStatus">
          <div>特价商品</div>
          <el-input
            v-if="detailInfo.canEdit"
            v-model="detailInfo.customerSpecialDiscount"
            placeholder="请输入"
            oninput="value=value.replace(/[^\d]/g,'');"
            @change="updateDiscount"
          >
            <template #suffix>%</template>
          </el-input>
          <span v-else>{{ detailInfo.customerSpecialDiscount || "-" }}%</span>
        </div>
      </div>
    </div>
    <div class="detail_right">
      <div class="right_title">
        <div class="title_opreate">
          <div class="opreate_left">
            <el-button v-if="canEdit" link @click="openSizeSettingModal()">
              <img src="@/assets/images/size-set.png" />
              <span class="btn_text">空间尺寸数据设置</span>
            </el-button>
            <span class="split_line" v-if="canEdit && detailInfo.showExchange === 1" />
            <el-button link @click="routeToExchange(1)" v-if="detailInfo.showExchange === 1">
              <img src="@/assets/images/back.png" />
              <span class="btn_text">退货单</span>
              <span class="corner_mark" v-if="detailInfo.returnProductNum > 0">
                {{ detailInfo.returnProductNum < 99 ? detailInfo.returnProductNum : "99+" }}
              </span>
            </el-button>
            <span class="split_line" v-if="detailInfo.showExchange === 1" />
            <el-button link @click="routeToExchange(2)" v-if="detailInfo.showExchange === 1">
              <img src="@/assets/images/change.png" />
              <span class="btn_text">换补单</span>
              <span class="corner_mark" v-if="detailInfo.replacementProductNum > 0">
                {{ detailInfo.replacementProductNum < 99 ? detailInfo.replacementProductNum : "99+" }}
              </span>
            </el-button>
          </div>
          <div class="opreate_right">
            <el-button class="primary_btn" @click="handleExport" :loading="exportLoading">导出报价表</el-button>
            <el-button class="right_btn" @click="goBack()">返回上一页</el-button>
          </div>
        </div>
        <div class="title_info" v-if="detailInfo.exchangeOrderList?.length > 0">
          <div
            class="info_box"
            v-for="(item, index) in detailInfo.exchangeOrderList.slice(0, showMore ? historyNum : 1)"
            :key="item.contractNo"
          >
            <div class="info_text">
              <span class="text_tag" :style="contractStatusList[item.contractStatus - 1]?.style">
                {{ contractStatusList[item.contractStatus - 1]?.text }}

                <!-- <span class="text_tag" :style="contractStatusList[item.contractStatus - 1]['style']"> -->
                <!-- {{ contractStatusList[item.contractStatus - 1]["text"] }} -->
              </span>
              {{ item.contractNo }}（
              <span class="info_label">类型：</span>
              <template v-if="item.afterSalesType === 1">整改</template>
              <template v-if="item.afterSalesType === 3">变更</template>
              <span class="info_label">金额：</span>
              ¥{{ item.exchangeAmount }}
              <span class="info_label">退货金额： </span>
              ¥{{ item.returnOrderAmount }}
              <span class="info_label">换补单金额：</span>
              ¥{{ item.replacementOrderAmount }}）
            </div>
            <div class="info_operate">
              <el-button class="info_btn" link type="primary" @click="openExchangeHistory(item)">
                查看
                <el-icon class="el-icon--right">
                  <ArrowRight />
                </el-icon>
              </el-button>
              <span v-if="index === 0 && historyNum > 1"> | </span>
              <el-button v-if="index === 0 && historyNum > 1" class="ml0" link type="primary" @click="showMore = !showMore">
                {{ !showMore ? "展开" : "收起" }}
                <el-icon class="el-icon--right">
                  <ArrowDown v-if="!showMore" />
                  <ArrowUp v-else />
                </el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <div id="table-content" class="right_content" ref="tableList">
        <div class="content_table" v-for="item in detailInfo.spaceList" :key="item.spaceId" :id="`space-${item.spaceId}`">
          <div class="table_title">
            {{ item.spaceName }}
            <div v-if="canEdit">
              <el-button type="primary" link @click="openSelectProd(item)">
                材料<img src="@/assets/images/download-icon.png" class="ml8" />
              </el-button>
              <el-divider direction="vertical" />
              <el-button type="primary" link @click="openQuota(item)">
                定额<img src="@/assets/images/download-icon.png" class="ml8" />
              </el-button>
              <el-divider direction="vertical" />
              <el-button type="primary" link @click="inventoryAddCustomFun(item, 'space-' + item.spaceId)">
                自定义定额
              </el-button>
            </div>
          </div>
          <spaceTable :tableData="item.spaceQuotaList" :budgetDetail="detailInfo" @success="successHandle" :canEdit="canEdit" />

          <!-- 软装模式下-每个空间下的明细表 -->
          <ruanzhaungDetailsTable
            v-if="currTempObj.softDecorationStatus === 1 && item?.quotaProductDetailsList?.length > 0"
            :tableData="item?.quotaProductDetailsList || []"
            @success="successHandle('备注修改成功')"
          />

          <div class="table_memo">
            <div class="memo_label">
              <span class="label">备注说明：</span>
              <RemarkEditor v-model="item.remark" :title="'修改备注'" :isEdit="canEdit" @submit="updateSpaceRemark(item)" />
            </div>
            <div class="memo_total">
              增项合计：<span class="total_num">¥ {{ item.spaceTotalMoney || "-" }}</span>
            </div>
          </div>
        </div>
        <div class="content_table" id="comprehensive" v-if="!(currTempObj.softDecorationStatus === 1)">
          <div class="table_title">
            <span>综合项</span>
            <el-button v-if="canEdit" type="primary" :icon="Plus" link @click="openAllroundDialog('add')"> 添加综合项 </el-button>
          </div>
          <el-table header-cell-class-name="table_head" :data="detailInfo.comprehensiveList" stripe border>
            <el-table-column label="序号" type="index" width="60" />
            <el-table-column prop="itemName" show-overflow-tooltip label="项目名称" width="100">
              <template #default="{ row }">{{ row.itemName || "-" }}</template>
            </el-table-column>
            <el-table-column prop="moneyType" label="属性" width="200">
              <template #default="{ row }">{{ row.moneyType === 1 ? "比例费用" : "固定费用" }}</template>
            </el-table-column>
            <el-table-column prop="linkTypesDesc" show-overflow-tooltip label="关联报价" width="150" />
            <el-table-column prop="originItemMoney" show-overflow-tooltip label="基数" width="150" />
            <el-table-column prop="feeRate" show-overflow-tooltip label="单价/比例" width="150" />
            <el-table-column prop="itemMoney" show-overflow-tooltip label="总价" width="150"></el-table-column>
            <el-table-column prop="remark" show-overflow-tooltip label="说明备注" min-width="150">
              <template #default="{ row }">{{ row.remark || "-" }}</template>
            </el-table-column>
            <el-table-column v-if="canEdit" fixed="right" label="操作" width="120">
              <template #default="{ row }">
                <el-button type="primary" link @click="openAllroundDialog('edit', row)">编辑</el-button>
                <el-button type="danger" link @click="deleteAllround(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="table_fee" v-if="!(currTempObj.softDecorationStatus === 1)">
            <div class="fee_box">
              <div class="box_title">
                <el-tooltip effect="dark" content="房屋测量总面积" placement="top">
                  <el-icon style="color: #909399">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                房屋测量总面积
              </div>
              <div class="box_text">
                <el-form-item label="总面积">
                  <el-input
                    :disabled="spaceParamList.some(item => item.area > 0) || !canEdit"
                    v-model.number="detailInfo.houseArea"
                    placeholder="-"
                    @change="updateBudgetDetail"
                  >
                    <template #suffix>㎡</template>
                  </el-input>
                </el-form-item>
              </div>
            </div>
            <div class="fee_box">
              <div class="box_title">
                <el-tooltip effect="dark" content="管理费=预算汇总表中的不含税造价X管理费率" placement="top">
                  <el-icon style="color: #909399">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                管理费
              </div>
              <div class="box_text">
                <el-form-item label="比例">
                  <el-input
                    :disabled="!canEdit"
                    v-model.number="detailInfo.managerFeeRate"
                    placeholder="-"
                    @change="updateBudgetDetail"
                  >
                    <template #suffix>%</template>
                  </el-input>
                </el-form-item>
              </div>
            </div>
            <div class="fee_box">
              <div class="box_title">
                <el-tooltip effect="dark" content="税金=(预算汇总表中的不含税造价+综合项+管理费)X税率" placement="top">
                  <el-icon style="color: #909399">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                税金费用
              </div>
              <div class="box_text">
                <el-form-item label="比例">
                  <el-input
                    :disabled="!canEdit"
                    v-model.number="detailInfo.taxesRate"
                    placeholder="-"
                    @change="updateBudgetDetail"
                  >
                    <template #suffix>%</template>
                  </el-input>
                </el-form-item>
              </div>
            </div>
          </div>
        </div>
        <!-- 软装模式下-汇总明细table -->
        <div id="summary-details" class="content_table" v-if="currTempObj.softDecorationStatus === 1">
          <div class="table_title">
            <p>汇总明细</p>
            <div class="jzt-flex-center">
              <p class="f14 jzt-flex-center mr10" style="width: 180px; font-weight: normal">
                <el-tooltip effect="dark" content="房屋测量总面积" placement="top">
                  <el-icon style="color: #909399">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                房屋测量总面积
              </p>
              <el-input
                :disabled="spaceParamList.some(item => item.area > 0) || !canEdit"
                v-model.number="detailInfo.houseArea"
                placeholder="-"
                @change="updateBudgetDetail"
              >
                <template #suffix>㎡</template>
              </el-input>
            </div>
          </div>
          <ruanzhaungSummaryDetailsTable :tableData="detailInfo?.aggregationVOList || []" />
        </div>
        <div id="summary" class="content_table" v-if="!(currTempObj.softDecorationStatus === 1)">
          <div class="table_title">
            <p>预算汇总表</p>
          </div>
          <el-table header-cell-class-name="table_head" :data="summaryData.itemList" stripe border>
            <el-table-column label="序号" type="index" width="60" />
            <el-table-column prop="itemName" label="分类别名" />
            <el-table-column prop="itemDesc" label="计算明细" />
            <el-table-column prop="amount" show-overflow-tooltip label="价格" width="300">
              <template #default="{ row }">¥{{ row.amount }}</template>
            </el-table-column>
          </el-table>
          <div class="table_memo">
            <div class="memo_label" style="width: 100%">
              <span class="label">备注说明：</span>
              <el-input
                v-model="summaryData.remark"
                :disabled="!canEdit"
                maxlength="200"
                placeholder="请输入"
                @change="updateSummaryRemark(summaryData.remark)"
              ></el-input>
            </div>
          </div>
        </div>
      </div>
      <div class="content_affix">
        <div style="width: 100%" position="bottom" :offset="21" target=".right_content">
          <div class="affix_content">
            <div v-if="detailInfo.isConcludeAmount" class="content_top">
              <div class="top_input" v-if="detailInfo.canEdit">
                <el-form-item label="成交金额">
                  <el-input v-model="detailInfo.concludeMoney" @change="updateConclude(detailInfo)">
                    <template #prefix>￥</template>
                  </el-input>
                </el-form-item>
                <el-form-item style="flex: 1" label="备注">
                  <el-input v-model="detailInfo.concludeRemark" @change="updateConclude(detailInfo)" maxlength="400" />
                </el-form-item>
              </div>
              <div v-else>
                <div class="top_title">
                  成交金额：<span class="title_num">{{ `￥${detailInfo.concludeMoney}` }}</span>
                </div>
                <div class="top_memo">备注：{{ detailInfo.concludeRemark }}</div>
              </div>
            </div>
            <div class="content_bottom">
              <div class="bottom_price">
                <div class="price_info">
                  <div class="info_title">
                    <span class="title_label">{{ detailInfo.budgetType === 1 ? "合计总造价：" : "套餐总价" }}</span>
                    <span class="title_num">¥{{ detailInfo.budgetTotlalMoney || "-" }}</span>
                    <template v-if="detailInfo.budgetType === 1">
                      {{
                        currTempObj.softDecorationStatus === 1
                          ? `（空间：${detailInfo.spaceItemNum || "-"}项
                        / 报价项：${detailInfo.budgetItemNum || "-"}项）`
                          : `（空间：${detailInfo.spaceItemNum || "-"}项
                        / 综合项：${detailInfo.comprehensiveNum || "-"}项
                        / 报价项：${detailInfo.budgetItemNum || "-"}项）`
                      }}
                    </template>
                    <template v-else>
                      {{
                        currTempObj.softDecorationStatus === 1
                          ? `（超出${detailInfo.overSquareNum || "-"}${useCodeArrStore().getDictName("shop_unit", detailInfo.packageUnitType) || "-"}：¥
                        ${detailInfo.overSquareNumMoney || "-"}+个性化增项/配：¥
                        ${detailInfo.customIncreaseMoney || "-"}）`
                          : `（超出${detailInfo.overSquareNum || "-"}${useCodeArrStore().getDictName("shop_unit", detailInfo.packageUnitType) || "-"}：¥
                        ${detailInfo.overSquareNumMoney || "-"}+个性化增项/配：¥
                        ${detailInfo.customIncreaseMoney || "-"}+管理费：¥
                        ${detailInfo.manageFee || "-"}）`
                      }}
                    </template>
                  </div>
                  <div class="info_code" v-if="detailInfo.budgetType === 1">预算编号：{{ detailInfo.budgetCustomNo }}</div>
                  <div class="bottom_info" v-if="detailInfo.budgetType === 2">
                    套餐价：
                    <span style="color: #1a1a1a">¥{{ detailInfo.packageUnitPrice || "-" }}</span>
                    元/{{ useCodeArrStore().getDictName("shop_unit", detailInfo.packageUnitType) || "-" }}
                    <span>{{
                      `（可享受${detailInfo.packageSquareNum || "-"}${useCodeArrStore().getDictName("shop_unit", detailInfo.packageUnitType) || "-"}/ 当前
                  ${detailInfo.houseArea || "-"}${useCodeArrStore().getDictName("shop_unit", detailInfo.packageUnitType) || "-"}，
                  每多出1${useCodeArrStore().getDictName("shop_unit", detailInfo.packageUnitType) || "-"}费用为：¥
                  ${detailInfo.packageOverUnitPrice || "-"}）`
                    }}</span>
                    <span>预算编号：{{ detailInfo.budgetCustomNo }}</span>
                    <span>{{
                      currTempObj.softDecorationStatus === 1
                        ? `（空间总数：${detailInfo.spaceItemNum || "-"}项 / 材料总数：
                  ${detailInfo.spaceItemNum || "-"}项`
                        : `（空间总数：${detailInfo.spaceItemNum || "-"}项 / 材料总数：
                  ${detailInfo.spaceItemNum || "-"}项 /  综合总数：
                  ${detailInfo.comprehensiveNum || "-"}项）`
                    }}</span>
                  </div>
                </div>
                <div class="price_operate">
                  <div v-if="!detailInfo.canCreateExchange">
                    <el-button
                      v-if="tempDetail.contractId && currTempObj.contractStatus !== 4"
                      class="primary_btn"
                      @click="handleEditContract()"
                      >修改合同
                    </el-button>
                    <el-button
                      v-if="(!tempDetail.budgetStatus && !tempDetail.contractId) || currTempObj.contractStatus === 4"
                      class="primary_btn"
                      @click="handleContract()"
                      >提交
                    </el-button>
                    <el-button
                      v-if="tempDetail.budgetStatus === 1 && !tempDetail.contractId"
                      class="primary_btn"
                      @click="handleCloseContract()"
                      >关闭订单
                    </el-button>
                  </div>
                  <el-button v-else class="primary_btn" @click="routeToChangeContract()">创建变更材料</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <editSpaceDialog
      v-if="editSpaceFlag"
      v-model="editSpaceFlag"
      :space="currentSpace"
      :budgetId="detailInfo.budgetId"
      @success="successHandle('空间名称修改成功')"
    />

    <ActionSubmitDialog
      v-model:isOpen="deleteDialogFlag"
      :title="deleteDialogOptions.title"
      :message="deleteDialogOptions.message"
      :submitBtnText="deleteDialogOptions.submitBtnText"
      @submit="deleteSubmitFn"
    />

    <sizeSettingModal
      v-model="sizeSettingFlag"
      :budgetId="detailInfo.budgetId"
      :spaceParamList="spaceParamList"
      @success="successHandle('空间尺寸数据修改成功')"
    />

    <!-- 添加综合项 -->
    <addAllroun v-model:isOpen="allroundDialogFlag" :optionInfo="allroundOptionInfo" @submitOk="successHandle('')" />

    <quota v-model:isOpen="quotaDialogFlag" :optionInfo="optionInfoQuota" @submitOk="successHandle()" />

    <selectProduct :optionInfo="prodOptionInfo" @close="closeSelectProDialog()" @submit="submitProSuccess()" />

    <exchangeHistoryModal
      v-if="exchangeHistoryFlag"
      v-model="exchangeHistoryFlag"
      :exchangeBudgetId="currentExchange.exchangeBudgetId"
    />
  </div>
</template>
<script setup>
import { computed, ref, watch, inject, nextTick } from "vue";
import editSpaceDialog from "./editSpaceDialog.vue";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import sizeSettingModal from "./sizeSettingModal.vue";
import RemarkEditor from "@/components/RemarkEditor";
import spaceTable from "./spaceTable.vue";
import addAllroun from "./addAllroun.vue";
import selectProduct from "./selectProduct.vue";
import quota from "./quota.vue";
import exchangeHistoryModal from "./exchangeHistoryModal.vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { ArrowDown, ArrowRight, ArrowUp, Plus } from "@element-plus/icons-vue";
import { setbudget, setHtml, setTableHtml, siveHtml } from "./setHtml.js";
import {
  spaceQueryCopy,
  spaceQueryDel,
  getSpaceParamList,
  getSummary,
  updateCustomerBudgetRemark,
  updateCustomerSpaceRemark,
  comprehensiveDel,
  packageAddCustom,
  inventoryAddCustom,
  updateBudgetQuotationFee,
  updateProductDiscount,
  updateConcludeInfo,
  exportOrder,
  exportDetail,
  exportPdf
} from "@/apis/quote-price/following";
import ruanzhaungDetailsTable from "./ruanzhuang-details-table.vue"; //每个空间的明细统计
import ruanzhaungSummaryDetailsTable from "./ruanzhuang-summary-details-table.vue"; //总的明细汇总
import useCodeArrStore from "@/store/modules/select";
import { documentFlow } from "@/utils/downFile";
import { selectDictDataByType } from "@/apis/dict/dict";

const currTempObj = ref(inject("currTemp")); //祖级传递过来的当前模板obj
const unitData = ref([]);
const moneyType = ref([]);
const contractStatusList = [
  { text: "待审核", style: "background: #FFF0D9;color:#FF9900" },
  { text: "已生效待整改", style: "background: #FFF0D9;color: #FF9900;" },
  { text: "进行中", style: "background: #D9EDFF;color: #409EFF;" },
  { text: "已通过", style: "background: #E8FFEA;color: #00B42A;" },
  { text: "审核不通过", style: "background: #FFC7C7;color: #FF3333;" },
  { text: "作废", style: "background: #CBD5E1;color: #4E5969;" }
];

const props = defineProps({
  tempDetail: {
    type: Object,
    default: () => {}
  },
  hasContract: { type: Boolean, default: false },
  customDetail: {
    type: Object,
    default: () => {}
  },
  nextPart: {
    type: Function,
    default: () => {}
  },
  originLength: { type: Number, default: 0 }
});

const emits = defineEmits(["refresh", "handleContract", "handleEditContract", "handleCloseContract"]);

const detailInfo = ref({});
const detailInfoCopy = ref({});
const canEdit = computed(() => !!detailInfo.value.canEdit);
const currViewSpaceId = ref(""); //记住再可视区域的空间id-spaceId

watch(
  () => props.tempDetail,
  (newVal, oldVal) => {
    detailInfo.value = JSON.parse(JSON.stringify(newVal));
    detailInfoCopy.value = JSON.parse(JSON.stringify(newVal));

    console.log("详情数据变化了===");
    detailInfo.value?.spaceList?.map(item => {
      if (!(currViewSpaceId.value && currViewSpaceId.value === item.spaceId)) {
        //非当前可视区域的空间table全部清空
        item.spaceQuotaList = [];
        item.quotaProductDetailsList = []; //软装模式下的明细表
      }
    });
    nextTick(() => {
      detailInfo.value?.spaceList?.map(item => {
        const div = document.getElementById(`space-${item.spaceId}`);
        // console.log("开始观察", div);
        // 开始观察
        observer.observe(div);
      });
      console.log("当前可视区域的空间ID", currViewSpaceId.value);
      if (currViewSpaceId.value) {
        detailInfo.value?.spaceList?.map(spaceObj => {
          if (spaceObj.spaceId === currViewSpaceId.value) {
            //当前可视区域的空间table不清空，但是重新赋值
            console.log("重新赋值", currViewSpaceId.value);
            const obj = detailInfoCopy.value?.spaceList?.find(o => o.spaceId === currViewSpaceId.value);
            spaceObj.spaceQuotaList = obj.spaceQuotaList;
            spaceObj.quotaProductDetailsList = obj.quotaProductDetailsList;
          }
        });
      }
    });
  },
  { deep: true }
);

const router = useRouter();

const tableList = ref();

const loading = ref(false);
const exportLoading = ref(false);
const editSpaceFlag = ref(false);
const deleteDialogFlag = ref(false);
const currentSpace = ref({});
const currentAllround = ref({});

const deleteDialogOptions = ref({ title: "提醒", message: "", submitBtnText: "继续" });
const deleteSubmitFn = ref();

const sizeSettingFlag = ref(false);
const spaceParamList = ref([]);

const allroundDialogFlag = ref(false);
const allroundOptionInfo = ref({ detail: {} });

const summaryData = ref({});

const quotaDialogFlag = ref(false);
const prodOptionInfo = ref({});
const optionInfoQuota = ref({});

const currentExchange = ref({});
const exchangeHistoryFlag = ref(false);

const showMore = ref(false);

const historyNum = computed(() => detailInfo.value.exchangeOrderList.length);

watch(
  () => currTempObj.value.budgetId,
  val => {
    setTimeout(() => {
      getSizeSetting(); //空间尺寸设置
      getSummaryData(); //查询预算汇总表单
    }, 500);
  },
  { deep: true }
);

const observer = new IntersectionObserver(
  entries => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        // 加载数据
        const item = entry.target;
        const spaceId = item.id?.split("-")[1];
        currViewSpaceId.value = spaceId;
        console.log("进入可视区域，加载数据", item.id?.split("-")[1], item);
        /**为当前可视区域的空间赋值 */
        detailInfo.value?.spaceList?.map(spaceObj => {
          if (spaceObj.spaceId === spaceId) {
            const obj = detailInfoCopy.value?.spaceList?.find(o => o.spaceId === spaceId);
            spaceObj.spaceQuotaList = obj.spaceQuotaList;
            spaceObj.quotaProductDetailsList = obj.quotaProductDetailsList;
          }
        });
      }
    });
  },
  {
    threshold: 0.5
  }
);

const goBack = () => router.push({ path: "/quote-price/following" });
const handleExport = async () => {
  exportLoading.value = true;
  try {
    const { data } = await exportDetail(detailInfo.value.budgetId);
    let budgetContent = "";
    if (data.softDecorationStatus !== 1) {
      budgetContent = setHtml(data, true);
      budgetContent += siveHtml(data, moneyType.value);
      budgetContent += setbudget(data);
    } else {
      budgetContent = setTableHtml(data, unitData.value);
    }
    const res = await exportPdf({
      budgetId: detailInfo.value.budgetId,
      budgetContent
    });
    documentFlow(res, detailInfo.value.budgetName, ".pdf");
    exportLoading.value = false;
  } catch (e) {
    exportLoading.value = false;
  }
};
const getUnit = async () => {
  const { data } = await selectDictDataByType("shop_unit");
  unitData.value = data || [];
};
const getMoneyType = async () => {
  const { data } = await selectDictDataByType("shop_budget_money_type");
  moneyType.value = data || [];
};
getUnit();
getMoneyType();
const editSpace = item => {
  editSpaceFlag.value = true;
  currentSpace.value = item;
};

const copySpace = async item => {
  currentSpace.value = item;
  const { code } = await spaceQueryCopy({
    spaceId: item.spaceId,
    budgetId: detailInfo.value.budgetId
  });
  code === 200 && successHandle("空间复制成功");
};

const deleteSpace = item => {
  currentSpace.value = item;
  deleteDialogOptions.value.message = "您正在删除导入的模板空间，请问是否继续当前操作？";
  deleteSubmitFn.value = deleteSpaceConfrim;
  deleteDialogFlag.value = true;
};

const deleteSpaceConfrim = async () => {
  const { code } = await spaceQueryDel({
    spaceId: currentSpace.value.spaceId,
    budgetId: detailInfo.value.budgetId
  });
  code === 200 && successHandle("空间删除成功");
  code === 200 && (deleteDialogFlag.value = false);
};

/**空间尺寸设置 列表 */
const getSizeSetting = async () => {
  if (currTempObj.value.budgetId) {
    const { code, data } = await getSpaceParamList(currTempObj.value.budgetId);
    code === 200 && (spaceParamList.value = data);
  } else {
    spaceParamList.value = [];
  }
};

const openSizeSettingModal = async () => {
  await getSizeSetting();
  sizeSettingFlag.value = true;
};

const openAllroundDialog = (type = "add", item) => {
  allroundOptionInfo.value.type = type;
  allroundOptionInfo.value.spaceList = detailInfo.value.spaceList;
  allroundOptionInfo.value.currTempObj = { budgetId: detailInfo.value.budgetId };
  allroundOptionInfo.value.detail = { ...item, _time: new Date().getTime() };
  allroundDialogFlag.value = true;
};

const deleteAllround = item => {
  currentAllround.value = item;
  deleteDialogOptions.value.message = "您正在删除综合项，请问是否继续当前操作？";
  deleteSubmitFn.value = deleteAllroundConfrim;
  deleteDialogFlag.value = true;
};

const deleteAllroundConfrim = async () => {
  const { code } = await comprehensiveDel({
    itemId: currentAllround.value.itemId,
    budgetId: detailInfo.value.budgetId
  });
  code === 200 && successHandle("综合项删除成功");
  code === 200 && (deleteDialogFlag.value = false);
};

const getSummaryData = async () => {
  if (currTempObj.value.budgetId) {
    const { code, data } = await getSummary({ budgetId: currTempObj.value.budgetId });
    code === 200 && (summaryData.value = data);
  } else {
    summaryData.value = {};
  }
};

const updateSummaryRemark = async remark => {
  const { code } = await updateCustomerBudgetRemark({ budgetId: detailInfo.value.budgetId, remark });
  code === 200 && successHandle("报价单预算汇总备注修改成功");
};

const updateSpaceRemark = async item => {
  const { code } = await updateCustomerSpaceRemark(item);
  code === 200 && successHandle("空间备注修改成功");
};

const openSelectProd = item => {
  prodOptionInfo.value.isShow = true;
  prodOptionInfo.value.spaceId = item.spaceId;
  prodOptionInfo.value.budgetId = detailInfo.value.budgetId;
  prodOptionInfo.value.type = detailInfo.value.budgetType;
};

const closeSelectProDialog = () => (prodOptionInfo.value.isShow = false);

const submitProSuccess = () => {
  prodOptionInfo.value.isShow = false;
  successHandle();
};

const openQuota = item => {
  quotaDialogFlag.value = true;
  optionInfoQuota.value.spaceId = item.spaceId;
  optionInfoQuota.value.budgetId = detailInfo.value.budgetId;
  optionInfoQuota.value.type = detailInfo.value.budgetType;
};

const inventoryAddCustomFun = async (item, domId) => {
  let apiFn = inventoryAddCustom;
  const param = { spaceId: item.spaceId, budgetId: detailInfo.value.budgetId };

  if (detailInfo.value.budgetType === 2) apiFn = packageAddCustom;

  const { code } = await apiFn(param);
  if (code === 200) {
    successHandle();

    document.getElementById("table-content").scrollBy({
      top: document.getElementById(domId).clientHeight - 60,
      behavior: "smooth"
    });
  }
};

const updateBudgetDetail = async () => {
  if (detailInfo.value.houseArea < 0 || detailInfo.value.managerFeeRate < 0 || detailInfo.value.taxesRate < 0) {
    return ElMessage({ message: "输入值必须大于0", type: "error" });
  }
  if (detailInfo.value.managerFeeRate > 100 || detailInfo.value.taxesRate > 100) {
    return ElMessage({ message: "输入值必须小于100", type: "error" });
  }
  const { code } = await updateBudgetQuotationFee({
    budgetId: detailInfo.value.budgetId,
    houseArea: detailInfo.value.houseArea,
    managerFeeRate: detailInfo.value.managerFeeRate,
    taxesRate: detailInfo.value.taxesRate
  });
  code === 200 && successHandle("修改成功");
};

const updateDiscount = async () => {
  await updateProductDiscount({
    budgetId: detailInfo.value.budgetId,
    customerRegularDiscount: detailInfo.value.customerRegularDiscount,
    customerSpecialDiscount: detailInfo.value.customerSpecialDiscount
  });
  successHandle("折扣修改成功");
};
const falg = ref(true);

const updateConclude = async ({ budgetId, concludeMoney, concludeRemark }) => {
  falg.value = false;
  await updateConcludeInfo({ budgetId, concludeMoney, concludeRemark });
  successHandle("修改成功");
};

const routeToExchange = orderType => {
  router.push({
    path: "/quote-price/following/exchange",
    query: {
      orderType,
      budgetId: detailInfo.value.budgetId,
      contractId: detailInfo.value.contractId,
      customerId: props.customDetail.customerId
    }
  });
};
// 发起合同 提交 发起订单
const handleContract = () => {
  if (falg.value === false) {
    loading.value = true;
    setTimeout(() => {
      emits("handleContract");
      loading.value = false;
    }, 2000);
  } else {
    emits("handleContract");
  }
  falg.value = true;
};
// 修改合同
const handleEditContract = () => {
  emits("handleEditContract");
};
// 关闭订单
const handleCloseContract = () => {
  emits("handleCloseContract");
};

const routeToChangeContract = () => {
  const routeUrl = router.resolve({
    path: "/quote-price/following/change",
    query: {
      budgetId: detailInfo.value.budgetId,
      contractId: detailInfo.value.contractId,
      customerId: props.customDetail.customerId,
      softDecorationStatus: currTempObj.value.softDecorationStatus
    }
  });

  window.open(routeUrl.href, "_blank");
};

const openExchangeHistory = item => {
  currentExchange.value = item;
  exchangeHistoryFlag.value = true;
};

const successHandle = (message, refresh = true) => {
  if (message) ElMessage({ message: message, type: "success" });

  getSummaryData(); //查询预算汇总表单
  refresh && emits("refresh");
};
</script>
<style lang="scss">
.temp_deatil {
  display: grid;
  grid-template-columns: 200px calc(100% - 200px);
  grid-template-rows: 100%;
  height: 100%;

  .detail_left {
    height: 100%;
    display: grid;
    grid-template-rows: calc(100% - 120px) 120px;
    border-right: 1px solid #e1e6ed;

    .left_top {
      box-sizing: border-box;
      padding: 10px 0px;
      height: 100%;
      overflow-y: auto;

      .el-anchor__list {
        padding: 0;
      }

      .el-anchor__marker {
        opacity: 0 !important;
      }

      .first_link {
        .el-anchor__link {
          padding: 10px 20px;
          font-weight: 700;
          font-size: 14px;
          color: #3d3d3d;
          line-height: 18px;
        }

        .is-active {
          color: white;
          background: #424e66;
        }

        .second_link {
          .el-anchor__link {
            font-size: 14px;
            font-weight: 400;
            color: #4e5969;
            background: #f2f3f5;
            padding: 10px 10px 10px 20px;
            display: flex;
            justify-content: space-between;
          }

          .is-active {
            color: white;
            background: #424e66;
          }
        }
      }
    }

    .left_bottom {
      display: grid;
      gap: 5px;
      border-top: 1px solid #e1e6ed;
      box-sizing: border-box;
      padding: 20px 10px;

      .bottom_discount {
        white-space: nowrap;
        display: flex;
        justify-content: center;
        flex-wrap: nowrap;
        align-items: center;
        gap: 10px;
      }
    }
  }

  .detail_right {
    display: grid;
    grid-template-rows: auto 1fr auto;
    grid-template-columns: 100%;
    height: 100%;
    overflow: hidden;

    .right_title {
      position: relative;
      box-shadow: 4px 5px 16px 0px #04134a0d;
      z-index: 1;

      .title_opreate {
        height: 50px;
        display: flex;
        justify-content: space-between;
        padding: 10px 20px 0;
        box-sizing: border-box;

        .opreate_left {
          display: flex;
          align-items: center;
          gap: 18px;

          .btn_text {
            color: #213270;
            margin-left: 8px;
          }

          .corner_mark {
            position: relative;
            bottom: 14px;
            right: 0;
            box-sizing: border-box;
            padding: 0 6px 0 5px;
            font-size: 12px;
            line-height: 18px;
            background: red;
            color: white;
            border-radius: 999px 999px 999px 0px;
          }

          .split_line {
            display: inline-block;
            width: 4px;
            height: 20px;
            border-radius: 2px;
            background: #dcdfe6;
          }
        }

        .opreate_right {
          .right_btn {
            background: #f2f3f5;
            color: #1d2129;
            border: 0;
            width: 120px;
          }

          .primary_btn {
            color: white;
            background: #424e66;
            border: 0;
          }
        }
      }

      .title_info {
        padding: 13px 20px;
        border-top: 1px solid #e1e6ed;

        .info_box {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .info_text {
            color: #3d3d3d;
            line-height: 24px;

            .text_tag {
              padding: 0 10px;
              border-radius: 2px;
              line-height: 20px;
            }

            .info_label {
              color: #86909c;
              margin-left: 5px;
            }
          }

          .info_operate {
            display: flex;
            gap: 10px;
            align-items: center;

            span {
              color: #213270;
            }
          }
        }
      }
    }

    .right_content {
      height: 100%;
      overflow: auto;
      background: #f5f7fa;

      .content_table {
        background: white;
        padding: 20px;
        margin-bottom: 20px;

        .table_head {
          background: #ebeef1;
        }

        .table_title {
          display: flex;
          justify-content: space-between;
          font-size: 18px;
          color: #3d3d3d;
          line-height: 24px;
          margin-bottom: 10px;
          font-weight: 700;
        }

        .table_memo {
          display: flex;
          justify-content: space-between;
          margin-top: 20px;

          .memo_label {
            display: flex;
            align-items: center;

            .label {
              min-width: 80px;
            }
          }

          .memo_total {
            font-weight: 700;

            .total_num {
              color: #ff3333;
            }
          }
        }

        .table_fee {
          display: flex;
          justify-content: space-between;
          margin-top: 20px;

          .fee_box {
            .box_title {
              display: flex;
              align-items: center;
              font-size: 16px;
              gap: 10px;
            }

            .box_text {
              display: flex;
              margin-top: 20px;
            }
          }
        }
      }
    }

    .content_affix {
      position: relative;
      z-index: 2;
      box-sizing: border-box;

      .affix_content {
        box-shadow: 1px -5px 10px 0px #424e6626;

        .content_top {
          background: white;
          padding: 8px 20px;
          border-bottom: 1px solid #c2d4e8;

          .top_input {
            display: flex;
            gap: 20px;

            .el-form-item {
              margin-bottom: 0px;
            }
          }

          .top_title {
            color: #606266;
            font-weight: 700;
            line-height: 24px;

            .title_num {
              color: #3d3d3d;
            }
          }

          .top_memo {
            color: #86909c;
            font-size: 12px;
            line-height: 24px;
          }
        }

        .content_bottom {
          box-sizing: border-box;
          background: white;
          padding: 10px 20px;
          height: 70px;

          .bottom_price {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .price_info {
              width: calc(100% - 100px);

              .info_title {
                line-height: 24px;
                color: #3d3d3d;

                .title_label {
                  font-weight: 700;
                  font-size: 16px;
                }

                .title_num {
                  color: #ff3333;
                  font-size: 16px;
                  font-weight: 700;
                }
              }

              .info_code {
                color: #86909c;
                font-size: 12px;
                line-height: 24px;
              }

              .bottom_info {
                line-height: 24px;
                font-size: 12px;
                color: #86909c;
                width: 100%;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
            }

            .primary_btn {
              color: white;
              background: #424e66;
              border: 0;
            }
          }
        }
      }
    }
  }

  .more_icon {
    transform: rotate(90deg);
    color: #86909c;
  }

  .is-disabled .el-input__wrapper {
    background: white !important;
  }
}

.operate_btns {
  width: 100%;

  .operate_btn {
    display: block;
    margin: 0;
    width: 100%;
    text-align: left;
    padding: 8px;
  }
}

.el-button--primary {
  --el-button-bg-color: #424e66;
  border: none;
}

.el-button.el-button--info {
  --el-color-info: #f2f3f5;
  --el-color-white: #1d2129;

  &:hover {
    --el-button-hover-bg-color: #f2f3f5 !important;
    border-color: #f2f3f5 !important;
  }
}
</style>
